package com.hangxin.word.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hangxin.common.utils.StringUtils;
import com.hangxin.word.domain.SimilarWordInfo;
import com.hangxin.word.domain.StandardWordInfo;
import com.hangxin.word.mapper.SimilarWordInfoMapper;
import com.hangxin.word.mapper.StandardWordInfoMapper;
import com.hangxin.word.service.ISimilarWordInfoService;
import com.hangxin.word.service.IStandardWordInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import static java.util.Arrays.stream;

/**
 * 相近词 Impl
 *
 * @author ZX
 */
@Service
public class StandardWordInfoImpl extends ServiceImpl<StandardWordInfoMapper, StandardWordInfo> implements IStandardWordInfoService {

    @Autowired
    private ISimilarWordInfoService similarWordInfoService;

    public List<StandardWordInfo> listWithSimilar(StandardWordInfo standardWordInfo) {
        String standardWord = standardWordInfo.getStandardWord();
        List<StandardWordInfo> list = lambdaQuery()
                .like(StringUtils.isNotBlank(standardWord), StandardWordInfo::getStandardWord, standardWord)
                .list();

        if (list.isEmpty()) {
            return list;
        }

        Set<Long> ids = list.stream().map(StandardWordInfo::getId).collect(Collectors.toSet());
        Map<Long, List<SimilarWordInfo>> map =
                similarWordInfoService.lambdaQuery()
                        .in(SimilarWordInfo::getStandardWordId, ids)
                        .list()
                        .stream()
                        .collect(Collectors.groupingBy(SimilarWordInfo::getStandardWordId));

        list.forEach(w -> w.setSimilarWords(map.getOrDefault(w.getId(), Collections.emptyList())));
        return list;
    }

    @Override
    public void confirmSimilar(List<Long> ids) {
        if (ids.isEmpty()) {
            return;
        }
        similarWordInfoService.lambdaUpdate()
                .set(SimilarWordInfo::getStatus, 1)
                .in(SimilarWordInfo::getId, ids)
                .update();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeStandardAndSimilar(Long id) {
        similarWordInfoService.lambdaUpdate()
                .eq(SimilarWordInfo::getStandardWordId, id)
                .remove();
        this.removeById(id);
        return 1;
    }
}
